import React from 'react'
import Admin from "../../../layout/Admin";
import AIModel from "../../../model/ai";
import moment from "moment";
import {Button, DatePicker, Divider, Input, Select} from "antd";
import echarts from 'echarts';
import NANO_ODDS_COMPANY_CODE from "./company";
import _ from 'lodash'
import {downloadExl} from "../../../model/excel";

const { RangePicker } = DatePicker;
const { Option } = Select;

const formatCompanyObjToArr = (obj) => {
    let arr = []
    for (let [id, name] of Object.entries(obj)) {
        arr.push({id: parseInt(id), name,})
    }

    return arr

}
const five = [
    {name: '英超',},
    {name: '意甲',},
    {name: '西甲',},
    {name: '德甲',},
    {name: '法甲',},
]

class AiResult extends React.Component {

    constructor(props) {
        super(props)
        this.model = new AIModel()
        this.state = {
            start: moment().subtract(1, 'day'),
            end: moment(),
            result: [],
            chart: null,
            categoryChart: null,
            name: '',
            company: [],
            nameTemp: '',
            names: [],
            namesOption: five,
        }
    }

    componentDidMount() {

        this.bindResizeEvent()
        let pie = this.initChart(this.chart)
        let category = this.initChart(this.categoryChart)
        setTimeout(() => {
            pie.resize()
            category.resize()
        })


        this.setState({
            chart: pie,
            categoryChart: category,
        }, () => {
            this.getResult()
                .then(() => {
                    this.setChart(pie)
                })
        })

    }

    bindResizeEvent = () => {
        const resizeCallback = _.debounce(() => {
            this.state.chart && this.state.chart.resize()
            this.state.categoryChart && this.state.categoryChart.resize()
        }, 100)
        window.addEventListener('resize', resizeCallback)
    }

    initChart = (chart) => {
        return echarts.init(chart)
    }

    setChart = (chart) => {
        const option = this.formatOption(this.state.result)
        chart.setOption(option)
    }

    onDateRangeChange = (value) => {
        let [start, end,] = value
        this.setState({
            start,
            end,
        }, () => {
            this.getResult()
                .then(() => {
                    this.setChart(this.state.chart)
                })
        })
    }

    getEvent = () => {
        this.model.getEventList()
            .then((res) => {
                let events = res.data.ok
                events.map((event, index) => {
                    const name = JSON.parse(event.Name)[0]
                    if (name === '瑞典超') {
                        console.log(event, index)
                    }
                })
                const promises = events.map(event => {
                    const p = this.model.result({
                        name: JSON.parse(event.Name)[0],
                        starttime: parseInt(this.state.start.format('X')),
                        endtime: parseInt(this.state.end.format('X')),
                    })
                    return p
                })
                return Promise.all(promises).then(resList => {
                    let resultList = []
                    resList.map((res, index) => {
                        const name = JSON.parse(events[index].Name)[0]
                        const data = res.data.ok
                        // 让球 胜平负 大小球
                        const rq = data[0]
                        const spf = data[1]
                        const dxq = data[2]
                        // resultList.push({
                        //     name: name,
                        //     all: dxq.All,
                        //     rate: dxq.Rate,
                        // })
                        const condition = dxq.All > 5 || rq.All > 5 || spf.All > 5
                        if (condition) {
                            resultList.push({
                                '联赛名': name,
                                '大小球': dxq.All,
                                '大小球准确率': dxq.Rate,
                                '让球': rq.All,
                                '让球准确率': rq.Rate,
                                '胜平负': spf.All,
                                '胜平负准确率': spf.Rate,
                            })
                        }
                    })
                    const sortByRate = resultList.sort((a, b) => b['大小球准确率'] - a['大小球准确率'])
                    return sortByRate
                })
            })
            .then((list) => {
                const quchong = []
                list.map(e => {
                    const index = quchong.findIndex(result => result.name === e.name)
                    if (index === -1) {
                        quchong.push(e)
                    }
                })
                console.log(quchong)
                list.map(d => console.log(`${d.name} 共 ${d.all}场 胜率 ${d.rate}`))
                downloadExl(list)
            })
    }

    getResult = () => {
        return this.model
            .result({
                name: this.state.name,
                starttime: parseInt(this.state.start.format('X')),
                endtime: parseInt(this.state.end.format('X')),
            })
            .then((res) => {
                const data = res.data.ok
                if (data) {
                    this.setState({
                        result: data,
                    })
                }
            })

    }

    getResultByNames = () => {

        const names = this.state.names
        if (names.length === 0) {
            this.getResult()
                .then(() => {
                    this.setChart(this.state.chart)
                })
        }
        const promises = names.map(name => {
            const p = this.model.result({
                name: name,
                starttime: parseInt(this.state.start.format('X')),
                endtime: parseInt(this.state.end.format('X')),
            })
            return p
        })
        Promise.all(promises)
            .then(respList => {
                let data = respList.map(resp => resp.data.ok)
                return data
            })
            .then(list => {
                const xAxisDate = names
                const series = [
                    {
                        data: [],
                        type: 'bar',
                        label: {
                            show: true,
                            position: 'inside',
                        },
                        showBackground: true,
                    },
                    {
                        data: [],
                        type: 'bar',
                        label: {
                            show: true,
                            position: 'inside',
                        },
                        showBackground: true,
                    },
                    {
                        data: [],
                        type: 'bar',
                        label: {
                            show: true,
                            position: 'inside',
                        },
                        showBackground: true,
                    },
                ]
                list.map(rateDate => {
                    rateDate.map((data, index) => {
                        series[index].data.push(parseFloat(data.Rate.toFixed(2)))
                    })
                })
                const option = {
                    xAxis: {
                        type: 'category',
                        data: xAxisDate,
                        axisLabel: {
                            interval:0,
                            rotate:40
                        },

                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: series,
                }
                this.state.categoryChart.setOption(option)
            })

    }

    getResultByCompany = () => {
        const company = this.state.company
        if (company.length === 0) {
            return this.getResult()
                .then(() => {
                    this.setChart(this.state.chart)
                })
        }
        return this.model
            .resultByCompany({
                name: this.state.name,
                starttime: parseInt(this.state.start.format('X')),
                endtime: parseInt(this.state.end.format('X')),
                // company: this.state.company,
                company: this.state.company,
            })
            .then((res) => {
                const data = res.data.ok
                if (data) {
                    data.forEach((odd) => odd.All = odd.Right + odd.Wrong)
                    this.setState({
                        result: data,
                    })
                }
            })
            .then(() => {
                this.setChart(this.state.chart)
            })
            .then(() => {
                let params = {
                    name: this.state.name,
                    starttime: parseInt(this.state.start.format('X')),
                    endtime: parseInt(this.state.end.format('X')),
                    // company: this.state.company,
                }
                return company.map(c => {
                    return this.model.resultByCompany({
                        ...params,
                        company: [c]
                    })
                })
            })
            .then((promises) => {
                let data = []
                return Promise.all(promises).then((respList) => {
                    respList.map(resp => {
                        data.push(resp.data.ok)
                    })
                    return data
                })
            })
            .then((list) => {
                const xAxisDate = this.state.company.map(id => NANO_ODDS_COMPANY_CODE[id])
                const series = [
                    {
                        data: [],
                        type: 'bar',
                        label: {
                            show: true,
                            position: 'inside',
                        },
                        showBackground: true,
                    },
                    {
                        data: [],
                        type: 'bar',
                        label: {
                            show: true,
                            position: 'inside',
                        },
                        showBackground: true,
                    },
                    {
                        data: [],
                        type: 'bar',
                        label: {
                            show: true,
                            position: 'inside',
                        },
                        showBackground: true,
                    },
                ]
                list.map(rateDate => {
                    rateDate.map((data, index) => {
                        series[index].data.push(parseFloat(data.Rate.toFixed(2)))
                    })
                })
                const option = {
                    xAxis: {
                        type: 'category',
                        data: xAxisDate,
                        axisLabel: {
                            interval:0,
                            rotate:40
                        },

                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: series,
                }
                this.state.categoryChart.setOption(option)
            })

    }

    addNameItem = () => {
        this.setState(({
            namesOption: [...this.state.namesOption, {name: this.state.nameTemp,}],
            nameTemp: '',
        }))
    }

    formatOption = (dataArr) => {

        const title = [
            {text: '小应预测概率'},
        ]
        const series = []

        dataArr.map((result, index) => {
            const titleTop = '90%'
            const titleMapper = {
                '0': {text:'让球预测概率', top: titleTop, left: '16.67%',},
                '1': {text:'胜负平预测概率', top: titleTop, left: '50%',},
                '2': {text:'大小球预测概率', top: titleTop, left: '83.33%',},
            }
            const right = result.Right
            const rightRate = ((result.Rate) * 100).toFixed(2)
            const wrongRate = 100 - rightRate
            const all = result.All
            const wrong = all - right
            const data = [
                {name: `正确:${rightRate}%` , value: right,},
                {name: `错误:${wrongRate}%`, value: wrong,}
            ]
            const positionMapper = {
                '0': {left: 0, right: '66.6667%', top: 0, bottom: 0,},
                '1': {left: '33.3333%', right: '33.3333%', top: 0, bottom: 0,},
                '2': {left: '66.6667%', right: 0, top: 0, bottom: 0,},
            }
            const pieOption = {
                label: {
                    normal: {
                        formatter: '{b}\n数量:{c}',
                    }
                },
                type: 'pie',
                radius: '50%',
                center: ['50%', '50%'],
                data: data,
                animation: true,
                ...positionMapper[index],
            }
            title.push({
                subtext: titleMapper[index].text,
                left: titleMapper[index].left,
                top: titleMapper[index].top,
                textAlign: 'center',
            })
            series.push(pieOption)
        })
        return {
            title,
            series,
        }


        // const right = rqDate.Right
        // const rightRate = ((rqDate.Rate) * 100).toFixed(2)
        // const wrongRate = 100 - rightRate
        // const all = rqDate.All
        // const wrong = all - right
        // const data = [
        //     {name: `正确:${rightRate}%` , value: right,},
        //     {name: `错误:${wrongRate}%`, value: wrong,}
        // ]
        // const options = {
        //     title: [
        //         {text: '小应预测概率',},
        //         {subtext: 'rq'}
        //     ],
        //     series: [{
        //         label: {
        //             normal: {
        //                 formatter: '{b}\n数量:{c}',
        //             }
        //         },
        //         type: 'pie',
        //         radius: '100%',
        //         center: ['50%', '50%'],
        //         data: data,
        //         animation: true,
        //     }]
        // }
        //
        // return data

    }


    onSelectChange = (value) => {
        const company = value.map(c => parseInt(c))
        this.setState({
            company,
        })
    }

    onSelectNameChange = (value) => {
        this.setState({
            names: value,
        })
    }

    render() {

        return <>
            <Admin>

                <div className='list-container'>
                    <RangePicker
                        showTime
                        style={{marginBottom: '16px'}}
                        defaultValue={[
                            moment().subtract(1, 'day'),
                            moment(),
                        ]}
                        onChange={(value) => {
                            this.onDateRangeChange(value)
                        }}
                    />
                    <div
                        style={{marginBottom: '16px'}}
                    >
                        <Input
                            placeholder="搜索单联赛"
                            value={this.state.name}
                            onChange={e => this.setState({name: e.target.value,})}

                            style={{ width: 200 }}
                        />
                        <Button
                            onClick={() => {
                                this.getResult()
                                    .then(() => this.setChart(this.state.chart))
                            }}
                        >搜索</Button>
                        <Button onClick={this.getEvent}>搜索全联赛(导出excel)</Button>
                    </div>

                    <div
                        style={{marginBottom: '16px'}}
                    >
                        <Select
                            mode="multiple"
                            style={{width: '50%',}}
                            placeholder="选择公司显示正确率"
                            defaultValue={[]}
                            onChange={this.onSelectChange}
                        >
                            {formatCompanyObjToArr(NANO_ODDS_COMPANY_CODE).map(company => {
                                return <Option key={company.id}>{company.name}</Option>
                            })}
                        </Select>

                        <Button
                            onClick={this.getResultByCompany}
                        >确定</Button>

                    </div>

                    <div
                        style={{marginBottom: '16px'}}
                    >
                        <Select
                            mode="multiple"
                            style={{width: '50%',}}
                            placeholder="选择联赛显示正确率"
                            onChange={this.onSelectNameChange}
                            dropdownRender={menu => (
                                <div>
                                    {menu}
                                    <Divider style={{ margin: '4px 0' }} />
                                    <div style={{ display: 'flex', flexWrap: 'nowrap', padding: 8 }}>
                                        <Input style={{ flex: 'auto' }} value={this.state.nameTemp} onChange={e => this.setState({nameTemp: e.target.value,})} />
                                        <a
                                            style={{ flex: 'none', padding: '8px', display: 'block', cursor: 'pointer' }}
                                            onClick={this.addNameItem}
                                        >
                                            添加联赛
                                        </a>
                                    </div>
                                </div>
                            )}
                        >
                            {this.state.namesOption.map(name => <Option key={name.name}>{name.name}</Option>)}
                        </Select>

                        <Button
                            onClick={this.getResultByNames}
                        >确定</Button>

                    </div>

                    <div
                        ref={el => this.chart = el}
                        style={{height: '500px', width: '100%',}}
                    />

                    <div
                        ref={el => this.categoryChart = el}
                        style={{height: '500px', width: '100%',}}
                    />

                </div>
            </Admin>
        </>
    }
}

export default AiResult
